package com.tianzeculture.stagebao.activity.video;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mabeijianxi.smallvideorecord2.LocalMediaCompress;
import com.mabeijianxi.smallvideorecord2.MediaRecorderActivity;
import com.mabeijianxi.smallvideorecord2.model.AutoVBRMode;
import com.mabeijianxi.smallvideorecord2.model.LocalMediaConfig;
import com.mabeijianxi.smallvideorecord2.model.OnlyCompressOverBean;
import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.activity.artist.ArtistEditPersonWorkActivity;
import com.tianzeculture.stagebao.activity.artist.HotTagActivity;
import com.tianzeculture.stagebao.activity.artist.adapter.PushWorksAdapter;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.WorkTag;
import com.tianzeculture.stagebao.net.ArtistRestUsage;
import com.tianzeculture.stagebao.network.Request;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.ToastUtil;
import com.tianzeculture.stagebao.util.ImageUtils;
import com.tianzeculture.stagebao.util.Util;
import com.tianzeculture.stagebao.view.MyRecyclerview;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.valuesfeng.picker.Picker;
import io.valuesfeng.picker.engine.GlideEngine;
import io.valuesfeng.picker.utils.PicturePickerUtils;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;


public class SendSmallVideoActivity extends BaseActivity implements PushWorksAdapter.WorksListener {

    //    private String videoUri;
//    private TextView tv_send;
//    private TextView tv_cancel;
//    private String videoScreenshot;
//    private ImageView iv_video_screenshot;
//    private EditText et_send_content;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_describe)
    EditText etDescribe;
    @BindView(R.id.tv_push)
    TextView tvPush;
    @BindView(R.id.my_recyclerview)
    MyRecyclerview myRecyclerview;
    @BindView(R.id.tvCharmTag)
    TextView tvCharmTag;
    @BindView(R.id.layoutCharmTag)
    LinearLayout layoutCharmTag;
    @BindView(R.id.btnSave)
    Button btnSave;

    private static final int REQUEST_CODE_CHOOSE = 1;
    private List<Uri> mSelected;
    private List<String> uris = new ArrayList<>();
    private AlertDialog dialog;
    boolean isVedio = true;
    PushWorksAdapter adapter;
    List<WorkTag> charmPosition = new ArrayList<>();
    List<WorkTag> checkCharmPosition = null;
    String charm;
    private int pushPhotoId = 100;
    private int pushVedioId = 210;
    Map<String, String> params = new HashMap<>();
    String videoUri;
    @Request
    ArtistRestUsage artistRestUsage = null;
    OnlyCompressOverBean onlyCompressOverBean;
    boolean flag;
    boolean buttonFlag;

    @Override
    protected int getLayoutResID() {
        return R.layout.smallvideo_text_edit_activity;
    }

    @Override
    public void initUI() {
        super.initUI();
        tvTitle.setText("展示设置");
        //布局管理器所需参数，上下文
        for (int i = 0; i < 5; i++) {
            WorkTag tag = new WorkTag();
            tag.setName(500 + i + "");
            charmPosition.add(tag);
        }
        Intent intent = getIntent();
        isVedio = intent.getBooleanExtra("isVideo", true);
        videoUri = intent.getStringExtra(MediaRecorderActivity.VIDEO_URI);
        // 选择本地视频压缩
        LocalMediaConfig.Buidler buidler = new LocalMediaConfig.Buidler();
        final LocalMediaConfig config = buidler
                .setVideoPath(videoUri)
                .captureThumbnailsTime(10)
                .doH264Compress(new AutoVBRMode())
                .setFramerate(15)
                .setScale(1.0f)
                .build();
        new Thread(new Runnable() {
            @Override
            public void run() {
                onlyCompressOverBean = new LocalMediaCompress(config).startCompress();
                flag = true;
            }
        }).start();
        if (flag)
            videoUri = onlyCompressOverBean.getVideoPath();
        if (isVedio) {
            uris.add(videoUri);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
//        {
//            @Override
//            public boolean canScrollVertically() {
//                return false;
//            }
//        };
        //B 通过布局管理器，可以控制条目排列顺序  true：反向显示  false：正常显示(默认)
//        gridLayoutManager.setReverseLayout(false);
//        //C 设置RecyclerView显示的方向，是水平还是垂直！！ GridLayoutManager.VERTICAL(默认) false
//        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
////        设置布局管理器 ， 参数 linearLayout

        myRecyclerview.setLayoutManager(gridLayoutManager);
        adapter = new PushWorksAdapter(this, uris, isVedio);
        adapter.setWorkListener(this);
        myRecyclerview.setAdapter(adapter);
    }


    //    private void initData() {
//        Intent intent = getIntent();
//        videoUri = intent.getStringExtra(MediaRecorderActivity.VIDEO_URI);
//        videoScreenshot = intent.getStringExtra(MediaRecorderActivity.VIDEO_SCREENSHOT);
//        Bitmap bitmap = BitmapFactory.decodeFile(videoScreenshot);
//        iv_video_screenshot.setImageBitmap(bitmap);
//        et_send_content.setHint("您视频地址为:" + videoUri);
//    }


//    private void initView() {
//        setContentView(R.layout.smallvideo_text_edit_activity);
//        tv_cancel = (TextView) findViewById(R.id.tv_cancel);
//        tv_send = (TextView) findViewById(R.id.tv_send);
//        et_send_content = (EditText) findViewById(R.id.et_send_content);
//        iv_video_screenshot = (ImageView) findViewById(R.id.iv_video_screenshot);
//    }

//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.tv_cancel:
//                hesitate();
//                break;
//            case R.id.tv_send:
//                break;
//            case R.id.iv_video_screenshot:
//                startActivity(new Intent(this, JianXiVideoPlayerActivity.class).putExtra(
//                        "path", videoUri));
//                break;
//        }
//    }


    @Override
    public void refreshUI(int taskId, MSG msg) {
        super.refreshUI(taskId, msg);
        if (taskId == pushPhotoId) {
            if (msg.getData())
                finish();
        }
        if (taskId == pushVedioId) {
            if (msg.getData()) {
                finish();
            }
        }
    }

    @OnClick({R.id.tvCharmTag, R.id.btnSave})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvCharmTag:
                Intent intent = new Intent(this, HotTagActivity.class);
                intent.putExtra("tagType", 3);//0风格标签 1外貌标签 2体型标签 3魅力部位
                intent.putExtra("Tag", (Serializable) charmPosition);
                startActivityForResult(intent, Util.HOT_TAG);
                break;
            case R.id.btnSave:
                if (buttonFlag)
                    return;
                if ("".equals(etTitle.getText().toString().trim())) {
                    ToastUtil.showShort(this, "标题不能为空");
                    return;
                }
                if ("".equals(etDescribe.getText().toString().trim())) {
                    ToastUtil.showShort(this, "作品描述不能为空");
                    return;
                }
                if (uris.size() == 0) {
                    ToastUtil.showShort(this, "请添加图片作品");
                    return;
                }
                params.put("title", etTitle.getText().toString().trim());
                params.put("title1", etDescribe.getText().toString().trim());

                if (isVedio) {
                    String image = ImageUtils.bitmapToBase64(getVideoThumb(videoUri));
                    params.put("title2", charm);
                    params.put("num", image);
                    params.put("videoFile", ImageUtils.fileToBase64(videoUri));
                    artistRestUsage.pushVedioWorks(pushVedioId, params);
                } else {
                    params.put("tag", charm);
                    artistRestUsage.pushPhotoWorks(pushPhotoId, params);
                }
                buttonFlag = true;
                break;
        }
    }

    public static Bitmap getVideoThumb(String path) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        return media.getFrameAtTime();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_CHOOSE:
                if (resultCode == RESULT_OK) {
                    if (data == null)
                        return;
                    params.clear();
                    uris.clear();
                    final List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
//                    mSelected = PicturePickerUtils.obtainResult(data);
                    for (int i = 0; i < path.size(); i++) {
                        uris.add(path.get(i));

                        final int finalI = i;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap bitmap = ImageUtils.compressImage(ImageUtils.getImageBitmap(path.get(finalI)));
                                String base64 = ImageUtils.bitmapToBase64(bitmap);
                                params.put("photoImgFile" + finalI, base64);
                            }
                        }).start();
                    }
                    adapter.setUriList(uris);
                    adapter.notifyDataSetChanged();
                }
                break;
            case Util.HOT_TAG:
                if (data == null)
                    return;
                Bundle bundle = data.getExtras();
                checkCharmPosition = (List<WorkTag>) bundle.getSerializable("checkTag");
                charm = getString(checkCharmPosition);
                updateUI(layoutCharmTag, checkCharmPosition);
                break;
        }
    }

    //拼接tag
    private String getString(List<WorkTag> list) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                sb.append(list.get(i).getName());
                break;
            }
            sb.append(list.get(i).getName());
            sb.append(",");
        }
        return sb.toString();
    }

    private void updateUI(LinearLayout layout, List<WorkTag> tags) {
        layout.removeAllViews();
        for (int i = 0; i < tags.size(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_work_tag, null);
            CheckBox boxWorkTag = view.findViewById(R.id.boxWorkTag);
            boxWorkTag.setChecked(true);
            boxWorkTag.setClickable(false);
            boxWorkTag.setText(tags.get(i).getName());
            view.setPadding(0, 0, 25, 0);
            layout.addView(view);
        }
    }

//    @Override
//    public void onBackPressed() {
//        hesitate();
//    }

    private void hesitate() {
        if (dialog == null) {
            dialog = new AlertDialog.Builder(this)
                    .setTitle(R.string.hint)
                    .setMessage(R.string.record_camera_exit_dialog_message)
                    .setNegativeButton(
                            R.string.record_camera_cancel_dialog_yes,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    finish();
//                                    FileUtils.deleteDir(getIntent().getStringExtra(MediaRecorderActivity.OUTPUT_DIRECTORY));
                                }

                            })
                    .setPositiveButton(R.string.record_camera_cancel_dialog_no,
                            null).setCancelable(false).show();
        } else {
            dialog.show();
        }
    }

    @Override
    public void workClick(int position, boolean isVideo) {
        if (isVideo) {
            startActivity(new Intent(this, JianXiVideoPlayerActivity.class).putExtra("path", videoUri));
        } else {
            if (position == uris.size()) {
//                Picker.from(this)
//                        .count(9)
//                        .enableCamera(true)
//                        .setEngine(new GlideEngine())
//                        .forResult(REQUEST_CODE_CHOOSE);
                MultiImageSelector.create()
                        .showCamera(true)
                        .count(9)
                        .multi()
                        .start(this, REQUEST_CODE_CHOOSE);
            }
        }
    }
}
